package com.xymtop.sqlcater.core.sql.sqlparser.tosql.life;


import com.xymtop.sqlcater.core.sql.sqlparser.tosql.entity.sql.BaseNode;
import com.xymtop.sqlcater.core.sql.sqlparser.tosql.entity.sql.Element;
import com.xymtop.sqlcater.core.sql.sqlparser.tosql.entity.sql.SqlNode;
import lombok.Data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Data
//元素构建
public class ElementBuilder {

    //基础节点列表
   private BaseNodeBuilder baseNodeBuilder;

   //元素列表
    private List<Element> elementList = new ArrayList<>();


    //构建元素
    public  ElementBuilder  build() throws IOException {

        //参数不能为空
        if(baseNodeBuilder != null && baseNodeBuilder.getBaseNodeList()!=null&&!baseNodeBuilder.getBaseNodeList().isEmpty()){
            for(BaseNode baseNode : baseNodeBuilder.getBaseNodeList()){
                //需要储存在这个元素里面
                Element element = new Element();
                //去除所有的引号
                if(baseNode.getKey().split("\"").length>1){

                    String name = baseNode.getKey().split("\"")[1];

                    //对元素的名称进行赋值
                    element.setName(name);

                }else {
                    element.setName(baseNode.getKey());
                }

                //对元素进行赋值
                element.setContent(baseNode);


                List<SqlNode> sqlNodeList = new ArrayList<>();
                //分割为sql节点
                String[] split = baseNode.getValue().split(" ");

                    //解析出sql节点
                    for (String nodeSql : split) {

                        SqlNodeBuilder sqlNodeBuilder = SqlNodeBuilder.add(nodeSql).build();
                        if (sqlNodeBuilder.getSqlNode() != null) {
                            sqlNodeList.add(sqlNodeBuilder.getSqlNode());
                        }

                    }
                    element.setSqlNodes(sqlNodeList);
                    if(element.getSqlNodes().size()==1){
                        element.setSql(element.getSqlNodes().get(0).getValue());
                    }

                //赋值完成
                elementList.add(element);
            }
        }

        return this;
    }


    //添加需要的数据
    public static ElementBuilder add(BaseNodeBuilder baseNodeBuilder){
        ElementBuilder elementBuilder = new ElementBuilder();
        elementBuilder.setBaseNodeBuilder(baseNodeBuilder);
        return elementBuilder;
    }
}
